<?php


namespace common\service;


use common\model\ContractModel;
use common\model\OrderModel;

class CustomerService
{

    /**
     * 客户列表
     * @param array $param
     * @param $tenantId
     * @return mixed
     * @throws \Exception
     */
    public function getCustomerList(array $param, $tenantId)
    {
        $res = teamones_request('teamones-im', 'customer/select', $param)['data'];
        if (empty($res['rows'])) {
            return $res;
        }

        $contractIdArray = [];
        foreach ($res['rows'] as $row) {
            if ((int)$row['framework_agreement_contract_id'] > 0) {
                $contractIdArray[] = $row['framework_agreement_contract_id'];
            }
        }
        $contractData = [];
        if (count($contractIdArray) > 0) {
            $contractData = model(ContractModel::class)->where(['id' => ['IN', implode(',', $contractIdArray)]])->select();
            $contractData = array_map(function ($c) {
                CommonService::getFormatAttrData(model(ContractModel::class), $c);
                return $c;
            }, $contractData);
            $contractData = array_column($contractData, null, 'id');
        }

        $fromTenantIds = array_column($res['rows'], 'tenant_id');
        $orderData = model(OrderModel::class) // 当前租户是乙方,接收到的订单数,列表的租户是甲方
        ->where(['to_tenant_id' => $tenantId, 'from_tenant_id' => ['IN', $fromTenantIds], 'status' => 'done'])
            ->field('count(*) as order_num,from_tenant_id')
            ->group('from_tenant_id')
            ->select();

        $orderMap = array_column($orderData, null, 'from_tenant_id');
        $res['rows'] = array_map(function ($row) use ($contractData, $orderMap) {
            $row['framework_agreement_contract'] = $contractData[$row['framework_agreement_contract_id']] ?? null;
            $row['find_order_num'] = $orderMap[$row['tenant_id']]['order_num'] ?? 0;
            return $row;
        }, $res['rows']);

        return $res;
    }

    /**
     * 查询
     * @param array $param
     * @return mixed
     * @throws \Exception
     */
    public function getCustomer(array $param)
    {
        $res = teamones_request('teamones-im', 'customer/find', $param)['data'];
        if (empty($res)) {
            return $res;
        }
        $res['framework_agreement_contract'] = null;
        if ((int)$res['framework_agreement_contract_id'] > 0) {
            $res['framework_agreement_contract'] = model(ContractModel::class)->where(['id' => $res['framework_agreement_contract_id']])->findData();
        }
        return $res;
    }
}
